package com.banyuan.servlet.user;

import org.apache.commons.io.FileUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;

@WebServlet("/user/login")
public class UserLoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;utf-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        boolean login = login(username, password);
        HttpSession session = req.getSession();

        if (login) {
            session.setAttribute("username",username);
            resp.getWriter().write("log success <a href=\"/web05/user/outlogin\">点击退出</a>\n");
        } else {
            resp.getWriter().write("log final");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }

    public boolean login(String username ,String password) throws IOException {
        boolean flag = false;
        List<String> list = FileUtils.readLines(new File("/Users/edy/Desktop/user2.txt"), "UTF-8");
        for (String s : list) {
            String[] split = s.split(",");
            if (username.equals(split[0]) && password.equals(split[1])) {
                flag = true;
                break;
            }
        }
        return flag;
    }


}
